import { Form, Input, InputNumber, Popconfirm, Table, Typography, Card } from 'antd';
import React, { useState, useEffect } from 'react';
import { getSettingList, updateConfigData, delConfigData } from '../../service';

interface Item {
    key: any;
    configKey: any;
    configValue: any;
}

interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
    editing: boolean;
    dataIndex: string;
    title: any;
    inputType: 'number' | 'text';
    record: Item;
    index: number;
    children: React.ReactNode;
}

const EditableCell: React.FC<EditableCellProps> = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
}) => {
    const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;

    return (
        <td {...restProps}>
            {editing ? (
                <Form.Item
                    name={dataIndex}
                    style={{ margin: 0 }}
                    rules={[
                        {
                            required: true,
                            message: `请输入${title}!`,
                        },
                    ]}
                >
                    {inputNode}
                </Form.Item>
            ) : (
                children
            )}
        </td>
    );
};

const App: React.FC = (props: any) => {
    console.log(props);
    let { query } = props;
    console.log(query);
    let originData: Item[] = [];
    const [form] = Form.useForm();
    const [data, setData] = useState(originData);
    const getSettingListData = () => {
        let params = {
            type: query.type,
        };
        getSettingList(params).then((res) => {
            if (res) {
                console.log(res);
                let { data } = res;
                data &&
                    data.forEach((item: any, index: any) => {
                        item.key = index;
                    });
                setData(data);
            }
        });
    };
    useEffect(() => {
        getSettingListData();
    });

    const [editingKey, setEditingKey] = useState('');

    const isEditing = (record: Item) => record.key === editingKey;

    const edit = (record: Partial<Item> & { key: React.Key }) => {
        form.setFieldsValue({ configKey: '', configValue: '', ...record });
        setEditingKey(record.key);
    };

    const cancel = () => {
        setEditingKey('');
    };
    const del = async (record: any) => {
        let params = {
            type: 'comment_conf',
            configKey: record.configKey,
            configValue: record.configValue,
        };
        console.log(params);
        delConfigData(params).then((res) => {
            if (res) {
                let { code } = res;
                if (code === '1') {
                    getSettingListData();
                }
            }
            setEditingKey('');
        });
    };

    const save = async (record: any) => {
        const row = (await form.validateFields()) as Item;
        console.log(row);
        let params = {
            type: 'comment_conf',
            configKey: row.configKey,
            configValue: row.configValue,
        };
        console.log(params);
        updateConfigData(params).then((res) => {
            if (res) {
                let { code } = res;
                if (code === '1') {
                    getSettingListData();
                }
            }
            setEditingKey('');
        });
    };

    const columns = [
        {
            title: 'configKey',
            dataIndex: 'configKey',
            width: '45%',
            editable: true,
        },
        {
            title: 'configValue',
            dataIndex: 'configValue',
            width: '40%',
            editable: true,
        },
        {
            title: '操作',
            dataIndex: '操作',
            width: '15%',
            render: (row: any, record: Item) => {
                const editable = isEditing(record);
                return editable ? (
                    <span>
                        <Typography.Link onClick={() => save(record)} style={{ marginRight: 8 }}>
                            Save
                        </Typography.Link>
                        <Popconfirm title="是否取消?" onConfirm={cancel}>
                            Cancel
                        </Popconfirm>
                    </span>
                ) : (
                    <span>
                        <Typography.Link
                            disabled={editingKey !== ''}
                            style={{ marginRight: 8 }}
                            onClick={() => edit(record)}
                        >
                            编辑
                        </Typography.Link>

                        <Popconfirm title="是否删除?" onConfirm={() => del(record)}>
                            删除
                        </Popconfirm>
                    </span>
                );
            },
        },
    ];

    const mergedColumns = columns.map((col) => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: (record: Item) => ({
                record,
                inputType: col.dataIndex === 'age' ? 'number' : 'text',
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEditing(record),
            }),
        };
    });

    return (
        <Card title="数据出境" bordered={false}>
            <Form form={form} component={false}>
                <Table
                    components={{
                        body: {
                            cell: EditableCell,
                        },
                    }}
                    bordered
                    dataSource={data}
                    columns={mergedColumns}
                    rowClassName="editable-row"
                    pagination={false}
                />
            </Form>
        </Card>
    );
};

export default App;
